package run.halo.app.service.impl;


import org.springframework.stereotype.Service;
import run.halo.app.cache.AbstractStringCacheStore;
import run.halo.app.exception.AuthenticationException;
import run.halo.app.model.entity.Follower;
import run.halo.app.model.entity.Post;
import run.halo.app.repository.FollowerRepository;
import run.halo.app.security.util.SecurityUtils;
import run.halo.app.service.FollowerService;
import run.halo.app.service.PostService;
import run.halo.app.service.UserService;
import run.halo.app.service.base.AbstractCrudService;

import java.util.Optional;

@Service
public class FollowerServiceImpl extends AbstractCrudService<Follower, Integer> implements FollowerService {
    private final FollowerRepository followerRepository;
    private final UserService userService;
    private final PostService postService;

    public FollowerServiceImpl( FollowerRepository followerRepository, UserService userService,PostService postService) {
        super(followerRepository);
        this.followerRepository = followerRepository;
        this.userService=userService;
        this.postService=postService;
    }


    @Override
    public void follow(Integer postId, String token) {
        Integer uid=userService.getCurrentUid(token);
        if (uid>0) {
            Post post = postService.getById(postId);
            Follower follower = new Follower();
            follower.setUid(uid);
            follower.setFid(post.getUid());
            follower.setFollow(1);
            super.create(follower);
        }
    }

    @Override
    public void notFollow(Integer postId, String token) {
        Integer uid=userService.getCurrentUid(token);
        if (uid>0) {
            Post post = postService.getById(postId);
            Follower follower = new Follower();
            follower.setUid(uid);
            follower.setFid(post.getUid());
            follower.setFollow(0);
            super.update(follower);
        }
    }

    private Integer getFollow(Integer uid, Integer fid) {
        Optional<Follower> of=followerRepository.getByUidAndFid(uid,fid);
        if (of.isPresent()) {
            Follower follower = of.get();
            return follower.getFollow();
        }
        else
            return 0;
    }

    @Override
    public Integer getIsFollow(String token, Integer fid){
        Integer uid=userService.getUidFromToken(token);
        if (uid>0) {
            uid = getFollow(uid, fid);
        }
        return uid;
    }



}
